#include	"../core/storage.h"
#include	"api_def.h"

static int Api_StorageGet(lua_State * pL) {
	const char * pKey = lua_tostring(pL, 1);
	std::string sValue = Storage::Get().Get(pKey);
	if (sValue.empty()) return 0;
	lua_pushlstring(pL, sValue.data(), sValue.length());
	return 1;
}

static int Api_StorageSet(lua_State * pL) {
	const char * pKey = lua_tostring(pL, 1);
	size_t nLen;
	const char * pValue = lua_tolstring(pL, 2, &nLen);
	bool bNeverExpire = lua_gettop(pL) > 2 ? lua_toboolean(pL, 3) == 1 : false;
	std::string sValue(pValue, nLen);
	Storage::Get().Set(pKey, sValue, bNeverExpire);
	return 0;
}

static int Api_StorageExpire(lua_State * pL) {
	lua_pushinteger(pL, Storage::Get().GetExpire());
	return 1;
}

void RegisterApi_Storage(lua_State * pL) {
	lua_newtable(pL);
	lua_setglobal(pL, "store");

	lua_getglobal(pL, "store");
	REGMETAAPI(pL, Api_StorageGet, "get");
	REGMETAAPI(pL, Api_StorageSet, "set");
	REGMETAAPI(pL, Api_StorageExpire, "expire");
	lua_pop(pL, 1);
}